﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
	<link href="js-console.css" rel="stylesheet" />
	<!-- 7. Write a program that finds the index of given 
			element in a sorted array of integers by using the 
			binary search algorithm (find it in Wikipedia) 
			
			In computer science, a binary search or half-interval search algorithm finds
			the position of a specified value (the input "key") within a sorted array.
			In each step, the algorithm compares the input key value with the key value of
			the middle element of the array. If the keys match, then a matching element has
			been found so its index, or position, is returned. Otherwise, if the sought key
			is less than the middle element's key, then the algorithm repeats its action
			on the sub-array to the left of the middle element or, if the input key is greater,
			on the sub-array to the right. If the remaining array to be searched is reduced
			to zero, then the key cannot be found in the array and a special "Not found"
			indication is returned. -->
</head>
<body>
	<div id="js-console"></div>
	<script src="js-console.js"></script>
	<script>
		var array = new Array();
		var element = parseInt(prompt("Enter element to search"));
		var number = parseInt(prompt("Enter number of elements"));
		if (!isNaN(number)) {
			// Enter the array of numbers
			for (var i = 0, j = 0; i < number; i++) {
				var n = parseInt(prompt("Enter element " + i));
				if (!isNaN(n)) {
					array[j] = n;
					j++;
				}
			}

			array.sort();
			jsConsole.writeLine("Sorted array: ");
			jsConsole.writeLine(array.join());
			jsConsole.writeLine("");

			// Do the search
			var index = -1;
			var flag = true;
			var low = 0;
			var high = array.length;
			var middle = 0;
			do
			{
				middle = parseInt((low + high) / 2);

				if (array[middle] == element)
				{
					flag = false;
					index = middle;
				}
				else
				{
					if (array[middle] < element)
					{
						low = middle + 1;
					}
					else
					{
						high = middle - 1;
					}
				}

				if (high < 0 || low == array.length)
				{
					flag = false;
					index = -2;
				}
			}
			while (flag);

			if (index >= 0) {
				jsConsole.writeLine("The index of " + element + " is " + index);
			}
			else {
				jsConsole.writeLine("Element with value " + element + " not found");
			}
		}
		else {
			jsConsole.writeLine("Wrong Input.");
		}
	</script>
</body>
</html>
